<template>
  <div>
    <el-container>
      <el-header style="background-color: #4c535a">
        <img src="@/assets/logo.png" alt="" style="width: 40px; position: relative; top: 10px;">
        <span style="font-size: 20px; margin-left: 15px; color: white">失能老人照料系统</span>
        <el-dropdown style="float: right; cursor: pointer; text-align: right; top: 20px;">
          <span class="el-dropdown-link" style="color:white; font-size: 16px">
            {{user.username}}
            <el-badge :value="recordsCount" :hidden="ifShowRecordsCount" :key="recordsCount">
              <i class="el-icon-arrow-down" style="margin-left: 5px"></i>
            </el-badge>
          </span>
          <el-dropdown-menu slot="dropdown" style="width: 100px; text-align: center">
            <el-dropdown-item style="font-size: 14px; padding: 5px 0;">
              <router-link style="text-decoration: none; color: #000" to="/person">个人信息</router-link>
            </el-dropdown-item>
            <el-dropdown-item style="font-size: 14px; padding: 5px 0;">
              <router-link style="text-decoration: none; color: #000" to="/message">
                消息
                <el-badge :value="recordsCount" :hidden="ifShowRecordsCount" :key="recordsCount"></el-badge>
              </router-link>
            </el-dropdown-item>
            <el-dropdown-item  style="font-size: 14px; padding: 5px 0;">
              <div @click="logout">退出登录</div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-header>
    </el-container>

    <el-container>
      <el-aside style="overflow: hidden; min-height: 100vh; background-color: #545c64; width: 250px">
        <el-menu :default-active="$route.path" router background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
          <el-menu-item index="/">
            <i class="el-icon-s-home"></i>
            <span slot="title">系统首页</span>
          </el-menu-item>
          <el-submenu index="2">
            <template slot="title">
              <i class="el-icon-user"></i><span>用户管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/user" v-if="adminVisible">用户信息</el-menu-item>
              <el-menu-item index="/familyMember">家庭成员</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-submenu index="3">
            <template slot="title">
              <i class="el-icon-document"></i><span>信息管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/health">健康信息</el-menu-item>
              <el-menu-item index="/sleep">睡眠信息</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-submenu index="4">
            <template slot="title">
              <i class="el-icon-goods"></i><span>服务</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/care">护理</el-menu-item>
            </el-menu-item-group>
            <el-menu-item-group>
              <el-menu-item index="/wheelchair">轮椅租赁</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-aside>
      <el-main>
        <router-view/>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import request from "@/utils/request";
import { Client } from '@stomp/stompjs';
import SockJS from 'sockjs-client';

export default {
  name: "Layout",

  data () {
    return {
      user: sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {},
      adminVisible: true,
      recordsCount: 0,
      stompClient: null,
      ifShowRecordsCount: true
    }
  },
  mounted() {
    this.checkUserType();
  },
  created() {
    this.getRecordsCount();
    this.connect();
  },
  methods:{
    logout() {
      sessionStorage.removeItem("user");
      localStorage.removeItem("menus");
      this.$router.push("/login");
      if (this.stompClient && this.stompClient.connected) {
        this.stompClient.publish({
          destination: '/app/stopGettingRecordsCount',
          body: `${this.user.id}` // 将用户ID作为消息体发送
        });
        console.log("已结束获取新记录量");
      }
    },
    checkUserType() {
      // 检查userType是否为0
      this.adminVisible = this.user.userType === 0;
    },
    getRecordsCount() {
      request.get("/invitation/search/count/invitee/"+this.user.id,).then(res => {
        if (res.code === '0') {
          this.recordsCount = res.data;
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    connect() {
      const socket = new SockJS('http://localhost:6174/ws');
      this.stompClient = new Client({
        webSocketFactory: () => socket,
        onConnect: () => {
          console.log('Getting records count WebSocket connected');

          // 连接成功后立即订阅
          this.stompClient.subscribe(`/topic/getRecordsCount/${this.user.id}`, message => {
            const count = parseInt(message.body);
            console.log('count: ' + count);
            this.recordsCount = count; // 更新数据展示
            console.log('Received records count:', count);
          });

          // 连接成功后立即发送开始获取记录量的请求
          this.stompClient.publish({
            destination: '/app/startGettingRecordsCount',
            body: `${this.user.id}` // 将用户ID作为消息体发送
          });
          console.log("已开始获取新记录量");
        },
        onStompError: (frame) => {
          console.error('Broker error: ' + frame.headers['message']);
          console.error('Details: ' + frame.body);
        }
      });
      this.stompClient.activate();
    }
  },
  watch: {
    recordsCount(newValue) {
      // 更新ifShowRecordsCount，当recordsCount不为0时，显示badge
      this.recordsCount = newValue;
      this.ifShowRecordsCount = this.recordsCount === 0;
    }
  }
}
</script>

<style>
.el-menu{
  border-right: none !important;
}
</style>
